package com.jt.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    /**
     * 该工具API主要任务
     * 1.根据cookie名称 返回cookie对象
     * 2.根据cookie名称 返回value的值
     * 3.新增cookie方法
     * 4.删除cookie方法
     */

    //根据cookie名称 返回cookie对象
    public static Cookie getCookie(String cookieName, HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }

        return null;
    }

    //根据cookie名称 返回value的值
    public static String getCookieValue(String cookieName, HttpServletRequest request) {
        Cookie cookie = getCookie(cookieName, request);
        return cookie == null ? null : cookie.getValue();
    }

    //新增cookie方法
    public static void addCookie(String cookieName, String cookieValue, String path, String domain, int maxAge, HttpServletResponse response) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    //删除cookie方法
    public static void deleteCookie(String cookieName, String path, String domain, HttpServletResponse response) {
        addCookie(cookieName, "", path, domain, 0, response);
    }
}
